package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.respository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {

        // MQL拼接语句
        Query query = new Query();

        // 分页对象 传入分页需要的参数 当前页-1  每页行数  排序规则  排序依据
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        // 返回分页对象
        // Page 是接口
        // PageImpl 是实现类
        return DBHelper.query(template, Region.class, query, pageable);
    }

    @Override
    public void saveOrUpdate(Region region) {

        if (StringUtils.hasText(region.getId())) {

            this.update(region);
        } else {
            this.save(region);
        }

    }


    @Override
    public void changeHotValue(String id, int hot) {

        // 部分字段更新
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);

        template.updateMulti(query, update, Region.class);

    }

    @Override
    public List<Region> queryHotRegion() {

        return regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }




}


































































